import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import LoginView from '../views/LoginView.vue'
import AdminHome from '@/components/AdminHome.vue'
import AdminUserVue from '@/components/AdminUser.vue'
import AdminRoleVue from '@/components/AdminRole.vue'
import AdminPermisVue from '@/components/AdminPermis.vue'
import AdminStudentVue from '@/components/AdminStudent.vue'
import AdminExamVue from '@/components/AdminExam.vue'
import AdminWorkVue from '@/components/AdminWork.vue'
import WorkSearchVue from '@/components/WorkSearch.vue'
import CheckWorkVue from '@/components/CheckWork.vue'
import AdminHostelVue from '@/components/AdminHostel.vue'
import inspectCheckVue from '@/components/inspectCheck.vue'
import AdminOverVue from '@/components/AdminOver.vue'
import RankChartVue from '@/components/RankChart.vue'
import ScoreChartVue from '@/components/ScoreChart.vue'
import AdminTrendVue from '@/components/AdminTrend.vue'
import PersonInfo from '@/components/PersonInfo.vue'
import { message } from "ant-design-vue";
import http from '../routerutils/http'
// 静态路由 - 无需权限
const staticRoutes = [
  {
    path: '/',
    name: 'home',
    component: () => import(/* webpackChunkName: "about" */ '../views/AdminView.vue'),
    meta: {
      isMenu: false,
    },
  },
  {
    path: '/login',
    name: 'Login',
    component: LoginView,
    meta: {
      isMenu: false,
    },
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/components/NotFound.vue'),
  },
  // {
  //   path: "/:catchAll(.*)",
  //   name: '404',
  //   redirect: '/404',
  //   // component: NotFoundVue
  // },
  // {
  //   path: '/404',
  //   name: 'NotFound',
  //   component: NotFoundVue,
  //   meta: {
  //     isMenu: false,
  //   },
  // }
];
// 动态路由 - 要根据角色的权限进行显示
export const dynamicRoutes: Array<RouteRecordRaw> = [
  {
    path: '/admin',
    name: 'admin',
    component: () => import(/* webpackChunkName: "about" */ '../views/AdminView.vue'),
    meta: {
      path: '/admin',
      isMenu: false,
      roles: ['SuperAdmin', 'SuperAdmin2', 'sutent', 'TeacherAdmin', 'InstructorAdmin', 'HostelAdmin']
    },
    children: [
      {
        path: 'home',
        name: 'home',
        component: AdminHome,
        meta: {
          isMenu: true,
          isHave: false,
          icon: "HomeOutlined",
          parent_title: "首页",
          path: '/admin/home',
          title: "首页",
          roles: ['SuperAdmin', 'SuperAdmin2', 'sutent', 'TeacherAdmin', 'InstructorAdmin', 'HostelAdmin']
        }
      },
      {
        path: 'permis',
        name: 'permis',
        meta: {
          isMenu: true,
          isHave: true,
          path: '/admin/permis',
          icon: "SettingOutlined", // 系统管理
          title: "系统管理",
          roles: ['SuperAdmin', 'SuperAdmin2']
        },
        children: [
          {
            path: 'user',
            name: 'user',
            component: AdminUserVue,
            meta: {
              isHave: false,
              isMenu: true,
              icon: "UserOutlined",
              parent_title: "系统管理",
              path: '/admin/permis/user',
              title: "用户管理",
              roles: ['SuperAdmin', 'SuperAdmin2']
            }
          },
          {
            path: 'role',
            name: 'role',
            component: AdminRoleVue,
            meta: {
              isHave: false,
              icon: "TeamOutlined", // 角色管理
              isMenu: true,
              parent_title: "系统管理",
              path: '/admin/permis/role',
              title: "角色管理",
              roles: ['SuperAdmin', 'SuperAdmin2']
            }
          },
          {
            path: 'permis',
            name: 'permis_permis',
            component: AdminPermisVue,
            meta: {
              isHave: false,
              isMenu: true,
              icon: "LockOutlined", // 权限管理
              parent_title: "系统管理",
              path: '/admin/permis/permis',
              title: "权限管理",
              roles: ['SuperAdmin', 'SuperAdmin2']
            }
          },
        ]
      },
      {
        path: 'student',
        name: 'student',
        component: AdminStudentVue,
        meta: {
          isHave: false,
          isMenu: true,
          icon: "UsergroupAddOutlined", // 学生管理
          parent_title: "学生管理",
          path: '/admin/student',
          title: "学生管理",
          roles: ['SuperAdmin', 'SuperAdmin2', 'sutent', 'TeacherAdmin', 'teacher', 'InstructorAdmin', 'HostelAdmin']
        }
      },
      {
        path: 'class',
        name: 'class',
        component: () => import('../components/AdminClass.vue'),
        meta: {
          isHave: false,
          isMenu: true,
          icon: "UsergroupAddOutlined", // 班级管理
          parent_title: "班级管理",
          path: '/admin/class',
          title: "班级管理",
          roles: ['SuperAdmin', 'SuperAdmin2', 'TeacherAdmin', 'InstructorAdmin', 'HostelAdmin']
        }
      },
      {
        path: 'exam',
        name: 'exam',
        component: AdminExamVue,
        meta: {
          isHave: false,
          isMenu: true,
          icon: "FileTextOutlined", // 考试管理
          parent_title: "考试管理",
          path: '/admin/exam',
          title: "考试管理",
          roles: ['SuperAdmin', 'SuperAdmin2', 'teacher', 'sutent', 'TeacherAdmin']
        }
      },
      {
        path: 'TeacherExam',
        name: 'TeacherExam',
        component: () => import("../components/TeacherExam.vue"),
        meta: {
          isHave: false,
          isMenu: true,
          icon: "FileTextOutlined", // 考试管理
          parent_title: "老师出题",
          path: '/admin/TeacherExam',
          title: "老师出题",
          roles: ['SuperAdmin', 'SuperAdmin2', 'teacher', 'sutent', 'TeacherAdmin']
        }
      },
      {
        path: 'work',
        name: 'work',
        meta: {
          isHave: true,
          path: '/admin/work',
          isMenu: true,
          title: "作业管理",
          icon: "FileOutlined", // 作业管理
          roles: ['SuperAdmin', 'SuperAdmin2', 'teacher', 'sutent', 'TeacherAdmin']
        },
        children: [
          {
            path: 'list',
            name: 'workList',
            component: AdminWorkVue,
            meta: {
              isHave: false,
              isMenu: true,
              icon: "OrderedListOutlined", // 作业列表
              parent_title: "作业管理",
              path: '/admin/work/list',
              title: "作业分析",
              roles: ['SuperAdmin', 'SuperAdmin2', 'teacher', 'sutent', 'TeacherAdmin']
            }
          },
          {
            path: 'search',
            name: 'search',
            component: WorkSearchVue,
            meta: {
              isHave: false,
              isMenu: true,
              icon: "SearchOutlined", // 表格分析
              parent_title: "作业分析",
              path: '/admin/work/search',
              title: "表格分析",
              roles: ['SuperAdmin', 'SuperAdmin2', 'teacher', 'sutent', 'TeacherAdmin']
            }
          },
        ]
      },
      {
        path: 'attend',
        name: 'attend',
        component: CheckWorkVue,
        meta: {
          isHave: false,
          isMenu: true,
          icon: "CalendarOutlined", // 考勤列表
          parent_title: "考勤管理",
          path: '/admin/attend',
          title: "考勤管理",
          roles: ['SuperAdmin', 'SuperAdmin2', 'teacher', 'sutent', 'TeacherAdmin', 'InstructorAdmin']
        }
      },
      {
        path: 'housekeep',
        name: 'housekeep',
        meta: {
          isHave: true,
          isMenu: true,
          icon: "HomeOutlined", // 内务管理
          parent_title: "内务管理",
          path: '/admin/housekeep',
          title: "宿舍管理",
          roles: ['SuperAdmin', 'SuperAdmin2', 'teacher', 'sutent', 'TeacherAdmin', 'InstructorAdmin', 'HostelAdmin']
        },
        children: [
          {
            path: 'info',
            name: 'info',
            component: AdminHostelVue,
            meta: {
              isHave: false,
              isMenu: true,
              icon: "HomeOutlined", // 宿舍信息
              parent_title: "内务管理",
              path: '/admin/housekeep/info',
              title: "宿舍信息",
              roles: ['SuperAdmin', 'SuperAdmin2', 'sutent', 'teacher', 'TeacherAdmin', 'InstructorAdmin', 'HostelAdmin']
            }
          },
          {
            path: 'inspect',
            name: 'inspect',
            component: inspectCheckVue,
            meta: {
              isHave: false,
              isMenu: true,
              icon: "SafetyOutlined", // 卫生管理
              parent_title: "内务检查",
              path: '/admin/housekeep/inspect',
              title: "卫生管理",
              roles: ['SuperAdmin', 'SuperAdmin2', 'sutent', 'teacher', 'TeacherAdmin', 'InstructorAdmin', 'HostelAdmin']
            }
          },
        ]
      },
      {
        path: 'count',
        name: 'count',
        meta: {
          isHave: true,
          title: "统计分析",
          path: '/admin/count',
          isMenu: true,
          icon: "PieChartOutlined", // 统计分析
          roles: ['SuperAdmin', 'SuperAdmin2', 'sutent', 'teacher', 'TeacherAdmin', 'InstructorAdmin', 'HostelAdmin']
        },
        children: [
          {
            path: 'overview',
            name: 'overview',
            component: AdminOverVue,
            meta: {
              isHave: false,
              isMenu: true,
              icon: "DashboardOutlined", // 概况统计
              parent_title: "统计分析",
              path: '/admin/count/overview',
              title: "概况统计",
              roles: ['SuperAdmin', 'SuperAdmin2', 'sutent', 'teacher', 'TeacherAdmin', 'InstructorAdmin', 'HostelAdmin']
            }
          },
          {
            path: 'rank',
            name: 'rank',
            component: RankChartVue,
            meta: {
              isHave: false,
              isMenu: true,
              icon: "TrophyOutlined", // 排名榜单
              parent_title: "统计分析",
              path: '/admin/count/rank',
              title: "排名榜单",
              roles: ['SuperAdmin', 'SuperAdmin2', 'sutent', 'teacher', 'TeacherAdmin', 'InstructorAdmin', 'HostelAdmin']
            }
          },
          {
            path: 'score',
            name: 'score',
            component: ScoreChartVue,
            meta: {
              isHave: false,
              isMenu: true,
              icon: "LineChartOutlined", // 学生成绩分析
              parent_title: "统计分析",
              path: '/admin/count/score',
              title: "学生成绩分析",
              roles: ['SuperAdmin', 'SuperAdmin2', 'sutent', 'teacher', 'TeacherAdmin', 'InstructorAdmin']
            }
          },
          {
            path: 'trend',
            name: 'trend',
            component: AdminTrendVue,
            meta: {
              isHave: false,
              isMenu: true,
              icon: "RiseOutlined", // 学习趋势分析
              parent_title: "统计分析",
              path: '/admin/count/trend',
              title: "学习趋势分析",
              roles: ['SuperAdmin', 'SuperAdmin2', 'sutent', 'teacher', 'TeacherAdmin', 'InstructorAdmin']
            }
          },
        ]
      },
      {
        path: 'sysset',
        name: 'sysset',
        meta: {
          isHave: true,
          isMenu: true,
          icon: "UserOutlined", // 个人设置
          parent_title: "个人设置",
          title: "个人设置",
          roles: ['SuperAdmin', 'SuperAdmin2', 'sutent', 'teacher', 'TeacherAdmin', 'InstructorAdmin', 'HostelAdmin']
        },
        children: [
          {
            path: 'personinfo',
            name: 'personinfo',
            component: PersonInfo,
            meta: {
              isHave: false,
              isMenu: true,
              icon: "ProfileOutlined", // 个人信息编辑
              parent_title: "个人信息",
              path: '/admin/sysset/personinfo',
              title: "个人信息编辑",
              roles: ['SuperAdmin', 'SuperAdmin2', 'sutent', 'teacher', 'TeacherAdmin', 'InstructorAdmin', 'HostelAdmin']
            }
          },
        ]
      },
    ]
  }
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes: staticRoutes,
})


// 获取当前用户拥有的权限--防止用户第二天登录vuex中无数据
// const getUserPermissions = async () => {
//   try{
//     const results = await http.get('/api/permissions/get_permissions')
//     console.log("获取当前用户拥有的权限成功：",results)
//     const userPermission = results.data.results.map((item:any)=>{
//       return item.permission_code
//     })
//     store.commit('SET_PERMISS',userPermission)
//   }catch(error){
//     console.log("获取当前用户拥有的权限失败：",error)
//   }
// }

// 导航守卫
// 导航守卫
router.beforeEach(async (to, from, next) => {
  // 1. 从localStorage获取认证信息
  const token = localStorage.getItem('token');
  const userRole = localStorage.getItem('role_code') || ''; // 默认空字符串表示无角色

  // 2. 处理根路径重定向
  if (to.path === '/') {
    return token ? next('/admin/home') : next('/login');
  }

  // 3. 如果路由不需要认证，直接放行
  if (!to.meta.requiresAuth) {
    return next();
  }

  // 4. 需要认证但用户未登录
  if (!token) {
    // 存储目标路由，登录后可以跳转回来
    localStorage.setItem('redirectUrl', to.fullPath);
    return next('/login');
  }

  // 5. 已登录用户禁止访问登录页
  if (to.name === 'Login') {
    return next('/admin/home');
  }

  // 6. 检查Token有效性（仅在需要认证的路由进行）
  try {
    const res = await http.get("/api/users/check");
    if (res.data.code !== 200) {
      throw new Error(res.data.message || 'Token验证失败');
    }
  } catch (error: any) {
    console.error("Token验证失败:", error);

    // 清除无效的认证信息
    localStorage.removeItem('token');
    localStorage.removeItem('role_code');

    // 根据错误类型显示不同提示
    const errorMsg = error.response?.data?.message || '登录已过期，请重新登录';
    message.error(errorMsg);

    // 存储目标路由，登录后可以跳转回来
    localStorage.setItem('redirectUrl', to.fullPath);
    return next('/login');
  }

  // 7. 检查路由权限要求
  if (to.meta.requiredRole && userRole !== to.meta.requiredRole) {
    // 更专业的做法是跳转到403页面
    return next('/403'); // 无权限页面
  }

  // 8. 默认放行
  next();
});

// router/index.ts
// 根据角色筛选出路由
function filterRoutesByRole(routes: any[], userRoles: string[]): any[] {
  return routes
    .map((route) => {
      // 复制路由对象避免修改原始数据
      const filteredRoute = { ...route };

      // 处理子路由（递归）
      if (route.children && route.children.length > 0) {
        filteredRoute.children = filterRoutesByRole(route.children, userRoles);
      }

      return filteredRoute;
    })
    .filter((route) => {
      // 过滤条件：无权限要求 或 有权限且用户有权限
      return (
        !route.meta?.roles ||
        route.meta.roles.some((role: string) => userRoles.includes(role))
      );
    });
}

// 根据路由动态创建菜单
export function generateDynamicRoutes() {
  const userRoles = localStorage.getItem("role_code") ? [localStorage.getItem("role_code")] : []
  // console.log(userRoles);
  const accessibleRoutes = filterRoutesByRole(dynamicRoutes, userRoles);

  // 先移除可能已存在的动态路由
  router.getRoutes().forEach((r) => {
    if (dynamicRoutes.some((dr) => dr.name === r.name)) {
      router.removeRoute(r.name!);
    }
  });

  // 添加新路由
  accessibleRoutes.forEach((route) => {
    // console.log("route>>>>>>>>>>", route);
    router.addRoute(route);
  });
}
// 每次加载调用一次，根据角色生成对应的路由
generateDynamicRoutes()



export default router
